﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Linq;

namespace CollectionViewSourceSpikes.Controls {
    internal class SourceHolder {

        private Dictionary<GroupingViewGroup, object> groupsHolder = new Dictionary<GroupingViewGroup,object>();
        private Dictionary<GroupingViewItem, object> itemsHolder = new Dictionary<GroupingViewItem, object>();

        public SourceHolder(GroupingView owner) {
            this.Owner = owner;
        }

        public GroupingView Owner { get; set; }

        public void AddGroup(GroupingViewGroup view, object source) {
            
            //TODO: Null check
            
            if (groupsHolder.ContainsKey(view)) {
                return;
            }
            groupsHolder.Add(view, source);

        }

        public void AddItem(GroupingViewItem view, object source) {

            //TODO: Null check

            if (itemsHolder.ContainsKey(view)) {
                return;
            }
            itemsHolder.Add(view, source);

        }

        public void Clear() {
            groupsHolder.Clear();
            itemsHolder.Clear();
        }

        public object SourceFromItemView(GroupingViewItem view) {
            if (!itemsHolder.ContainsKey(view)) {
                return null;
            }
            return itemsHolder[view];
        }

        public GroupingViewItem ItemViewFromSource(object source) {
            foreach (GroupingViewItem key in itemsHolder.Keys) {
                object value = itemsHolder[key];
                if (value == source) {
                    return key;
                }
            }
            return null;
        }

        public GroupingViewItem FindPreviousItem(GroupingViewItem target) {
            
            GroupingViewItem previous = null;
            foreach(GroupingViewItem item in  this.itemsHolder.Keys){
                if (target == item) {
                    return previous;
                }
                previous = item;
            }
            return null;
        }

        public GroupingViewItem FindNextItem(GroupingViewItem target) {

            bool matched = false;
            foreach (GroupingViewItem item in this.itemsHolder.Keys) {
                if (matched) {
                    return item;
                }
                if (target == item) {
                    matched = true;
                }
            }
            return null;
        }

        public GroupingViewItem FirstItem() {
            return this.itemsHolder.Keys.FirstOrDefault();
        }
    }
}
